#!/usr/bin/perl
# Version 0.2.1

$testcase = "spf";

# 1 = PASS
# 2 = FAIL
# 3 = INCONCLUSIVE
$verdict = 3;

$dumpfile = "$testcase.dump";
$logfile = "$testcase.log";

if ($#ARGV ne 0) {
        print("Usage: $testcase.pl log_file");
        exit 1;
}

$logfile = $ARGV[0];

#------------------------------------------------------------------------------

# router config
@ifc = ( "0.0.0.30", "0.0.0.13", "0.0.0.18" );
# this should be the routing table
@networks = ( "0.0.0.0/30", "0.0.0.4/30", "0.0.0.8/30", "0.0.0.12/30", "0.0.0.16/30", 
				"0.0.0.20/30", "0.0.0.24/30", "0.0.0.28/30");
@cost     = ( 11, 5, 7, 1, 2, 4, 3, 1 );
@nexthops = ( "1", "1", "2", "1", "2", "2", "0", "0" );

# Open the logfile
$success = 1;

@fwd_tbl = {};
$in_tbl = 0;

$errs = 0;

open(LOGFILE, $logfile) or $success = 0;

if ($success eq 1) {
	while(<LOGFILE>) {
		if($in_tbl eq 0) {
			# look for the beginning of a fwd table
			if(/OSPF Router 3(.*)Routing Table(.*)Content is now:/) {
				# yepp... found a new routing table
				$in_tbl = 1;
				@fwd_tbl = {};
			}
		} else {
			# look for the end of the fwd_table
			if(/---------------/) {
				# found the beginning or end...
				if($in_tbl eq 1) {
					# beginning
					$in_tbl = 2;
				} else {
					#end
					$in_tbl = 0;
				}
			} elsif(/N\s+(.*?)\s+(\d*?)\s+(.*?)\s+(\d*?)\s+(.*?)\s+/) {
				# save the RT entries
				$rt_entry = "$4 $5";
				$fwd_tbl{$1} = $rt_entry;
			}
		}
			
	}
	close(LOGFILE);
	
	# now look if the results are ok and give a verdict...
	if($in_tbl ne 0) {
		print("Premature end of logfile. ");
		$verdict = 3;
	} else {
		
		$verdict = 1;
		
		for ($i = 0; $i <= $#networks; $i++) {
			if( exists $fwd_tbl{$networks[$i]} ) {
				@rt_entry = split(/ /,$fwd_tbl{$networks[$i]});
				if($rt_entry[0] ne $cost[$i]) {
					# wrong cost
					$verdict = 2;
					
					$errs = $errs | 1;
				}
				@nh = split(/\|/, $rt_entry[1]);
				@nh_must = split(/ /, $nexthops[$i]);
				
				if($#nh ne $#nh_must) {
					# wrong number of next hops
					$verdict = 2;
					$errs = $errs | 2;
				} else {
					for($j = 0; $j <= $#nh_must; $j++) {
						if(index($rt_entry[1], $ifc[$nh_must[$j]]) eq -1) {
							# necessary next hop not found!
							$verdict = 2;
							$errs = $errs | 4;
						}
					}
				}	
			} else {
				# no route for a destiation
				$verdict = 2;
				$errs = $errs | 8;
			}
		}
	}
}

if ($verdict eq 1) {
	print("Routing table is built correctly. Test PASSED.\n");
} elsif ($verdict eq 2) {
	print("Routing table contains errors ($errs). Test FAILED.\n");
} else {
	print("Cannot evaluate Results. Test INCONCLUSIVE.\n");
}

#------------------------------------------------------------------------------
print("### VERDICT for $testcase: ");

if ($verdict eq 1) { 
        print("PASS"); 
} elsif ($verdict eq 2) {
        print("FAIL");
} else {
        print("INCONCLUSIVE");
}

print(" ###\n");